import { RootState } from '@/types/store'
import { Input, NavBar, TextArea } from 'antd-mobile'
import { InputRef } from 'antd-mobile/es/components/input'
import { TextAreaRef } from 'antd-mobile/es/components/text-area'
import { useEffect, useRef, useState } from 'react'
import { useSelector } from 'react-redux'

import styles from './index.module.scss'

type Props = {
  hideInput: () => void;
  onFinish: (tpye: string, val: string) => void;
  type: string;
};

const EditInput = (props: Props) => {
  // 拿取之前的数据
  const userProfile = useSelector(
    (state: RootState) => state.profile.userProfile
  )
  const [value, setValue] = useState(() => {
    return props.type === 'name' ? userProfile.name : userProfile.intro
  })
  //   绑定ref
  const inputRef = useRef<InputRef>(null)
  const textAreaRef = useRef<TextAreaRef>(null)
  //   数据回填
  useEffect(() => {
    inputRef.current?.focus()
    textAreaRef.current?.focus()
    // 原生操作
    const textarea = document.querySelector('textarea') as HTMLTextAreaElement
    // 开始和结束都是最后面
    textarea?.setSelectionRange(-1, -1)
  }, [])
  //   提交数据
  const updateHandler = () => {
    if (!value) {
      setValue('')
    }
    if (props.type === 'name' && value === '') return
    props.onFinish(props.type, value)
  }
  return (
    <div style={{ width: '100vw', height: '100vh' }} className={styles.root}>
      <NavBar
        onBack={props.hideInput}
        className="navbar"
        right={
          <span onClick={updateHandler} className="commit-btn">
            提交
          </span>
        }
      >
        编辑 {props.type === 'name' ? '昵称' : '简介'}
      </NavBar>

      <div className="edit-input-content">
        <h3>{props.type === 'name' ? '昵称' : '简介'}</h3>
        <div className="input-wrap">
          {props.type === 'name'
            ? (
            <div className="input-wrap">
              <Input
                ref={inputRef}
                value={value}
                onChange={(e) => {
                  setValue(e)
                }}
                placeholder="请输入昵称"
              />
            </div>
              )
            : (
            <TextArea
              className="textarea"
              placeholder="请输入简介"
              value={value}
              onChange={(e) => {
                setValue(e)
              }}
              showCount
              ref={textAreaRef}
              maxLength={99}
            />
              )}
        </div>
      </div>
    </div>
  )
}

export default EditInput
